package com.ponhu.ea2.goodsCenter.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ponhu.ea2.dto.PhInventoryGoodsEditDto;
import com.ponhu.ea2.entity.Goods;
import com.ponhu.ea2.entity.GoodsInventoryMd;
import com.ponhu.ea2.enums.ResponseCodeEnum;
import com.ponhu.ea2.goodsCenter.provider.biz.PonHuGoodsService;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsInventoryMdService;
import com.ponhu.ea2.support.exception.BusinessRuntimeException;
import com.ponhu.ea2.goodsCenter.provider.mapper.GoodsMapper;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsService;
import com.ponhu.ea2.goodsCenter.provider.utils.ProBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
@DubboService(version = "1.0.0", interfaceClass = GoodsService.class, timeout = 60000)
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private GoodsInventoryMdService goodsInventoryMdService;

    /**
     * 编辑货品关联商品基本信息
     *
     * @param editDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void editInventoryGoodsPrices(PhInventoryGoodsEditDto editDto) {

        Goods goods = ProBeanUtils.copyProperties(editDto, Goods.class)
                .setId(editDto.getGoodsId())
                .setUpdatedById(editDto.getOperatorId().intValue())
                .setUpdatedByName(editDto.getOperatorName())
                .setUpdatedTime(LocalDateTime.now());

        if (!updateById(goods)) {
            throw new BusinessRuntimeException(ResponseCodeEnum
                    .INVENTORY_EDIT_EXCEPTION_800208);
        }
    }

    @Override
    public Goods getGoodsByInventoryId(Long inventoryId) {
        LambdaQueryWrapper<GoodsInventoryMd> queryWrapper = Wrappers
                .lambdaQuery(GoodsInventoryMd.class)
                .eq(GoodsInventoryMd::getInventoryId, inventoryId)
                .last("LIMIT 1");

        GoodsInventoryMd md = goodsInventoryMdService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(md)) return null;

        return getById(md.getGoodsId());
    }
}




